<template>
  <div class="stock-in-order-add-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>新增入库单（伍智文）</h2>
      <div class="header-actions">
        <el-button @click="handleCancel">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>
    </div>

    <!-- 基础信息区域 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="stock-in-form"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="入库单号">
              <el-input v-model="formData.stockInCode" placeholder="自动按规则系统编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库类型" prop="inOutTypeId">
              <el-select
                v-model="formData.inOutTypeId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="进货入库" :value="1" />
                <el-option label="销售退货" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库名称" prop="warehouseId">
              <el-select
                v-model="formData.warehouseId"
                placeholder="请选择"
                filterable
                style="width: 100%"
                :loading="warehouseLoading"
              >
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.id"
                  :label="warehouse.name"
                  :value="warehouse.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="入库日期" prop="stockInDate">
              <el-date-picker
                v-model="formData.stockInDate"
                type="date"
                placeholder="请选择"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联单号">
              <el-input
                v-model="formData.relatedOrderCode"
                placeholder="请选择"
                readonly
                style="width: calc(100% - 50px)"
              />
              <el-button
                link
                type="primary"
                style="margin-left: 5px"
                @click="openPurchaseOrderDialog"
              >
                ...
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商ID">
              <el-input v-model="formData.supplierId" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input v-model="formData.contactPerson" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input v-model="formData.contactPhone" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经办人" prop="userId">
              <el-select
                v-model="formData.userId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="user in userList"
                  :key="user.user_Id"
                  :label="user.userTrueName || user.userName"
                  :value="user.user_Id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 入库明细区域 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>入库明细</span>
          <div>
            <el-button type="success" @click="openGoodsDialog">
              添加
            </el-button>
            <el-button @click="handleRemoveSelected">
              移除
            </el-button>
          </div>
        </div>
      </template>

      <!-- 明细列表 -->
      <el-table 
        :data="formData.orderItems" 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="货品名称" prop="goodsName" width="150" />
        <el-table-column label="货品编号" prop="goodsCode" width="120" />
        <el-table-column label="规格型号" prop="specificationModel" width="120" />
        <el-table-column label="单位" prop="unitName" width="100" />
        <el-table-column label="当前库存" prop="currentInventory" width="100" align="right" />
        <el-table-column label="进货数量" prop="purchaseQuantity" width="100" align="right" />
        <el-table-column label="已入库数量" prop="inStockedQuantity" width="120" align="right">
          <template #default="{ row }">
            {{ row.inStockedQuantity || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="未入库数量" prop="unStockedQuantity" width="120" align="right">
          <template #default="{ row }">
            {{ row.unStockedQuantity || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="入库库位" width="150">
          <template #default="{ row, $index }">
            <el-select
              v-model="row.stockPositionId"
              placeholder="请选择"
              style="width: 100%"
              size="small"
            >
              <el-option
                v-for="location in storageLocationList"
                :key="location.id"
                :label="location.locationName"
                :value="location.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="本次入库数量" width="150">
          <template #default="{ row, $index }">
            <el-input
              v-model="row.thisTimeQuantity"
              placeholder="请输入"
              type="number"
              size="small"
              style="width: 100%"
              @input="calculateItemAmount($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="进货单价" width="120" align="right">
          <template #default="{ row }">
            {{ row.purchasePrice || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="进货金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ (row.upprice || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="批次号" width="150">
          <template #default="{ row }">
            <el-input v-model="row.batchNo" placeholder="" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="生产日期" width="150">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.productionDate"
              type="date"
              placeholder="yyyy/mm/dd"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              size="small"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150">
          <template #default="{ row }">
            <el-input
              v-model="row.remark"
              placeholder=""
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              @click="removeItem($index)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 合计信息 -->
      <div class="total-summary">
        <div class="summary-display">
          <span class="summary-item">本次入库数量: <span class="count">{{ totalThisTimeQuantity }}</span></span>
          <span class="summary-item">已入库数量: <span class="count">{{ totalInStockedQuantity }}</span></span>
          <span class="summary-item">未入库数量: <span class="count">{{ totalUnStockedQuantity }}</span></span>
          <span class="summary-item">进货数量: <span class="count">{{ totalPurchaseQuantity }}</span></span>
          <span class="summary-item highlight">入库金额: <span class="amount">¥{{ totalAmount.toFixed(2) }}</span></span>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button type="success" @click="handleSave" :loading="saveLoading">
        <el-icon><Check /></el-icon>
        保存
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
      <el-button @click="handleCancel">
        <el-icon><Close /></el-icon>
        取消
      </el-button>
    </div>
  </div>

  <!-- 进货单选择对话框 -->
  <el-dialog
    v-model="purchaseOrderDialogVisible"
    title="选择进货单"
    width="80%"
    :close-on-click-modal="false"
  >
    <div class="dialog-content">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="purchaseOrderSearch">
          <el-form-item label="进货单号">
            <el-input
              v-model="purchaseOrderSearch.orderCode"
              placeholder="请输入进货单号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="单据状态">
            <el-select
              v-model="purchaseOrderSearch.status"
              placeholder="请选择"
              clearable
              style="width: 150px"
            >
              <el-option label="草稿" :value="0" />
              <el-option label="待审核" :value="1" />
              <el-option label="已完成" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select
              v-model="purchaseOrderSearch.supplierId"
              placeholder="请选择"
              clearable
              filterable
              style="width: 200px"
            >
              <el-option
                v-for="supplier in supplierList"
                :key="supplier.id"
                :label="supplier.supplierName"
                :value="supplier.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="resetPurchaseOrderSearch">重置</el-button>
            <el-button type="success" @click="searchPurchaseOrders">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 进货单列表 -->
      <el-table
        :data="purchaseOrderList"
        border
        style="width: 100%"
        height="400px"
        @row-click="handlePurchaseOrderSelect"
        highlight-current-row
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="orderCode" label="进货单号" width="180" show-overflow-tooltip />
        <el-table-column prop="statusText" label="单据状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getPurchaseOrderStatusType(row.status)">
              {{ getPurchaseOrderStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderDate" label="进货日期" width="120" />
        <el-table-column prop="supplierName" label="供应商" width="150" show-overflow-tooltip />
        <el-table-column prop="contact" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系方式" width="120" />
        <el-table-column prop="totalQuantity" label="进货数量" width="100" align="right" />
        <el-table-column prop="totalAmount" label="进货金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ (row.totalAmount || 0).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="purchaseOrderPagination.pageIndex"
          v-model:page-size="purchaseOrderPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="purchaseOrderPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadPurchaseOrders"
          @current-change="loadPurchaseOrders"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="purchaseOrderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPurchaseOrderSelection">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 货品选择对话框 -->
  <el-dialog
    v-model="goodsDialogVisible"
    title="添加货品"
    width="90%"
    :close-on-click-modal="false"
  >
    <div class="dialog-content">
      <div class="dialog-info" v-if="selectedPurchaseOrder">
        <span>进货单号：{{ selectedPurchaseOrder.orderCode }}</span>
        <span style="margin-left: 20px">进货日期：{{ selectedPurchaseOrder.orderDate }}</span>
        <span style="margin-left: 20px">供应商：{{ selectedPurchaseOrder.supplierName }}</span>
        <span style="margin-left: 20px">金额：¥{{ (selectedPurchaseOrder.totalAmount || 0).toFixed(2) }}</span>
        <span style="margin-left: 20px">数量：{{ selectedPurchaseOrder.totalQuantity || 0 }}</span>
      </div>

      <!-- 货品列表 -->
      <el-table
        :data="goodsList"
        border
        style="width: 100%; margin-top: 15px"
        height="400px"
        @selection-change="handleGoodsSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="goodsCode" label="货品编号" width="120" show-overflow-tooltip />
        <el-table-column prop="goodsName" label="货品名称" width="150" show-overflow-tooltip />
        <el-table-column prop="specModel" label="规格型号" width="120" />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="purchasePrice" label="进货单价" width="100" align="right" />
        <el-table-column prop="purchaseQuantity" label="进货数量" width="100" align="right" />
        <el-table-column prop="amount" label="进货金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ (row.amount || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="inStockedQuantity" label="已入库" width="100" align="right" />
        <el-table-column prop="unStockedQuantity" label="未入库" width="100" align="right" />
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="goodsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmGoodsSelection">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Check, 
  Close, 
  Refresh
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 获取实例
const { proxy } = getCurrentInstance()
const router = useRouter()

// 响应式数据
const formRef = ref()
const saveLoading = ref(false)
const purchaseOrderDialogVisible = ref(false)
const goodsDialogVisible = ref(false)
const warehouseLoading = ref(false)

// 基础数据列表
const warehouseList = ref([])
const userList = ref([])
const supplierList = ref([])
const unitList = ref([])
const storageLocationList = ref([])
const purchaseOrderList = ref([])
const goodsList = ref([])

// 选中的数据
const selectedPurchaseOrder = ref(null)
const selectedGoods = ref([])
const selectedItems = ref([])

// 进货单搜索
const purchaseOrderSearch = reactive({
  orderCode: '',
  status: '',
  supplierId: ''
})

// 进货单分页
const purchaseOrderPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  stockInCode: '',
  inOutTypeId: 1, // 默认采购入库
  warehouseId: null,
  stockInDate: '',
  relatedOrderCode: '',
  supplierId: null,
  contactPerson: '',
  contactPhone: '',
  userId: null,
  remark: '',
  status: 0,
  orderItems: []
})

// 表单验证规则
const formRules = {
  inOutTypeId: [{ required: true, message: '请选择入库类型', trigger: 'change' }],
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  stockInDate: [{ required: true, message: '请选择入库日期', trigger: 'change' }],
  userId: [{ required: true, message: '请选择经办人', trigger: 'change' }]
}

// 计算总金额
const totalAmount = computed(() => {
  return formData.orderItems.reduce((sum, item) => sum + (parseFloat(item.upprice) || 0), 0)
})

// 计算总数量
const totalThisTimeQuantity = computed(() => {
  return formData.orderItems.reduce((sum, item) => sum + (parseFloat(item.thisTimeQuantity) || 0), 0)
})

const totalInStockedQuantity = computed(() => {
  return formData.orderItems.reduce((sum, item) => sum + (parseFloat(item.inStockedQuantity) || 0), 0)
})

const totalUnStockedQuantity = computed(() => {
  return formData.orderItems.reduce((sum, item) => sum + (parseFloat(item.unStockedQuantity) || 0), 0)
})

const totalPurchaseQuantity = computed(() => {
  return formData.orderItems.reduce((sum, item) => sum + (parseFloat(item.purchaseQuantity) || 0), 0)
})

// 获取仓库列表
const fetchWarehouseList = async () => {
  warehouseLoading.value = true
  try {
    const response = await proxy.http.post('/api/warehousemodel/GetPageData', {
      pageIndex: 1,
      pageSize: 1000
    }, false)
    
    if (response && (response.status === 0 || response.status === true || response.status === 1)) {
      let data = []
      
      if (response.rows && Array.isArray(response.rows)) {
        data = response.rows
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        data = response.data.rows
      } else if (Array.isArray(response.data)) {
        data = response.data
      }
      
      warehouseList.value = data.map(item => ({
        id: item.Id || item.id,
        name: item.WarehouseName || item.warehouseName || item.name
      })).filter(item => item.id && item.name)
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  } finally {
    warehouseLoading.value = false
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const response = await proxy.http.get('/api/InboundManagement/GetUserOptions', {}, false)
    
    if (response && response.success) {
      userList.value = response.data || []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 获取供应商列表
const fetchSupplierList = async () => {
  try {
    const response = await proxy.http.post('/api/suppliermodel/GetPageData', {
      pageIndex: 1,
      pageSize: 1000
    }, false)
    
    if (response && response.status) {
      const data = response.rows || response.data?.rows || []
      supplierList.value = data.map(supplier => ({
        id: supplier.Id || supplier.id,
        supplierName: supplier.SupplierName || supplier.supplierName
      }))
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error)
  }
}

// 获取单位列表
const fetchUnitList = async () => {
  try {
    console.log('正在获取单位列表...')
    const response = await proxy.http.post('/api/unitmodel/GetPageData', {
      pageIndex: 1,
      pageSize: 1000
    }, false)
    
    console.log('单位列表API响应:', response)
    
    if (response && (response.status === 0 || response.status === true || response.status === 1)) {
      let data = []
      
      if (response.rows && Array.isArray(response.rows)) {
        data = response.rows
      } else if (response.data?.data && Array.isArray(response.data.data)) {
        data = response.data.data
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        data = response.data.rows
      } else if (Array.isArray(response.data)) {
        data = response.data
      }
      
      console.log('原始单位数据:', data)
      
      if (data.length > 0) {
        unitList.value = data.map(unit => ({
          id: unit.Id || unit.id,
          unitName: unit.UnitName || unit.unitName || unit.name,
          unitCode: unit.UnitCode || unit.unitCode || unit.code
        })).filter(item => item.id && item.unitName)
        
        console.log('处理后的单位数据:', unitList.value)
      } else {
        unitList.value = []
      }
    }
  } catch (error) {
    console.error('获取单位列表失败:', error)
    unitList.value = []
  }
}

// 获取出入库类型列表
const fetchInOutTypeList = async () => {
  inOutTypeLoading.value = true
  try {
    const response = await proxy.http.post('/api/inouttypemodel/GetPageData', {
      pageIndex: 1,
      pageSize: 100
    }, false)
    
    if (response && (response.status === 0 || response.status === true || response.status === 1)) {
      let data = []
      
      if (response.rows && Array.isArray(response.rows)) {
        data = response.rows
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        data = response.data.rows
      }
      
      // 只获取入库类型（1:进货入库，2:销售退货）
      inOutTypeList.value = data.filter(item => {
        const typeId = item.Id || item.id
        return typeId === 1 || typeId === 2
      }).map(item => ({
        id: item.Id || item.id,
        typeName: item.TypeName || item.typeName || item.name
      }))
    }
  } catch (error) {
    console.error('获取出入库类型失败:', error)
  } finally {
    inOutTypeLoading.value = false
  }
}

// 获取库位列表
const fetchStorageLocationList = async () => {
  try {
    const response = await proxy.http.post('/api/storagelocationmodel/GetPageData', {
      pageIndex: 1,
      pageSize: 1000
    }, false)
    
    if (response && (response.status === 0 || response.status === true || response.status === 1)) {
      let data = []
      
      if (response.rows && Array.isArray(response.rows)) {
        data = response.rows
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        data = response.data.rows
      }
      
      storageLocationList.value = data.map(location => ({
        id: location.Id || location.id,
        locationName: location.LocationName || location.locationName || location.name
      })).filter(item => item.id && item.locationName)
    }
  } catch (error) {
    console.error('获取库位列表失败:', error)
  }
}

// 打开进货单选择对话框
const openPurchaseOrderDialog = () => {
  purchaseOrderDialogVisible.value = true
  loadPurchaseOrders()
}

// 获取进货单列表
const loadPurchaseOrders = async () => {
  try {
    const params = {
      pageIndex: purchaseOrderPagination.pageIndex,
      pageSize: purchaseOrderPagination.pageSize,
      ...purchaseOrderSearch
    }
    
    // 清理空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    console.log('获取进货单列表，参数:', params)
    
    const response = await proxy.http.get('/api/PurchaseOrderModel/GetPageList', params, false)
    
    console.log('进货单列表API响应:', response)
    
    // 修复：status 为 0 也是成功状态
    if (response && (response.status === 0 || response.status === true || response.status === 1)) {
      let data = []
      
      // 优先检查 response.rows，因为数据可能直接在顶层
      if (response.rows && Array.isArray(response.rows)) {
        data = response.rows
      } else if (response.data?.data && Array.isArray(response.data.data)) {
        data = response.data.data
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        data = response.data.rows
      } else if (Array.isArray(response.data)) {
        data = response.data
      }
      
      console.log('进货单原始数据:', data)
      
      purchaseOrderList.value = data.map(order => ({
        ...order,
        orderCode: order.OrderCode || order.orderCode,
        orderDate: order.OrderDate || order.orderDate,
        supplierId: order.SupplierId || order.supplierId,
        supplierName: order.SupplierName || order.supplierName,
        contact: order.Contact || order.contact,
        contactPhone: order.ContactPhone || order.contactPhone,
        totalQuantity: order.TotalQuantity || order.totalQuantity,
        totalAmount: order.TotalAmount || order.totalAmount,
        status: order.Status || order.status
      }))
      purchaseOrderPagination.total = response.total || data.length
      
      console.log('处理后的进货单列表:', purchaseOrderList.value)
      console.log('总数:', purchaseOrderPagination.total)
    } else {
      console.error('进货单API响应状态异常:', response)
      purchaseOrderList.value = []
      purchaseOrderPagination.total = 0
    }
  } catch (error) {
    console.error('获取进货单列表失败:', error)
    ElMessage.error('获取进货单列表失败，请检查网络连接')
    purchaseOrderList.value = []
    purchaseOrderPagination.total = 0
  }
}

// 搜索进货单
const searchPurchaseOrders = () => {
  purchaseOrderPagination.pageIndex = 1
  loadPurchaseOrders()
}

// 重置进货单搜索
const resetPurchaseOrderSearch = () => {
  purchaseOrderSearch.orderCode = ''
  purchaseOrderSearch.status = ''
  purchaseOrderSearch.supplierId = ''
  searchPurchaseOrders()
}

// 选择进货单
const handlePurchaseOrderSelect = (row) => {
  selectedPurchaseOrder.value = row
}

// 确认选择进货单
const confirmPurchaseOrderSelection = () => {
  if (!selectedPurchaseOrder.value) {
    ElMessage.warning('请选择一个进货单')
    return
  }
  
  const order = selectedPurchaseOrder.value
  
  // 自动反填进货单信息
  formData.relatedOrderCode = order.orderCode
  formData.supplierId = order.supplierId
  formData.contactPerson = order.contact
  formData.contactPhone = order.contactPhone
  
  purchaseOrderDialogVisible.value = false
  
  console.log('已选择进货单，自动反填信息:', {
    关联单号: formData.relatedOrderCode,
    供应商ID: formData.supplierId,
    联系人: formData.contactPerson,
    联系方式: formData.contactPhone
  })
  
  ElMessage.success(`已选择进货单：${order.orderCode}，供应商信息已自动填写`)
}

// 获取进货单状态类型
const getPurchaseOrderStatusType = (status) => {
  const statusMap = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取进货单状态文本
const getPurchaseOrderStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '已完成',
    3: '驳回'
  }
  return statusMap[status] || '未知'
}

// 打开货品选择对话框
const openGoodsDialog = () => {
  if (!formData.relatedOrderCode) {
    ElMessage.warning('请先选择关联进货单号')
    return
  }
  
  goodsDialogVisible.value = true
  loadGoods()
}

// 获取货品列表
const loadGoods = async () => {
  try {
    if (!formData.relatedOrderCode) {
      return
    }
    
    const params = {
      orderCode: formData.relatedOrderCode
    }
    
    console.log('获取进货单货品，参数:', params)
    
    const response = await proxy.http.get('/api/WarehousingManagement/GetPurchaseOrderGoods', params, false)
    
    console.log('货品API响应:', response)
    
    if (response && response.success) {
      goodsList.value = (response.data || []).map(goods => ({
        goodsId: goods.goodsId,
        goodsCode: goods.goodsCode,
        goodsName: goods.goodsName,
        specModel: goods.specModel,
        unitId: goods.unitId,
        unitName: goods.unitName,
        currentInventory: goods.currentInventory || 0,  // ✅ 添加当前库存
        purchasePrice: goods.purchasePrice,
        purchaseQuantity: goods.purchaseQuantity,
        inStockedQuantity: goods.inStockedQuantity || 0,
        unStockedQuantity: goods.unStockedQuantity,
        amount: goods.amount
      }))
      
      console.log('处理后的货品列表:', goodsList.value)
    }
  } catch (error) {
    console.error('获取货品列表失败:', error)
    ElMessage.error('获取货品列表失败')
  }
}

// 货品选择变化
const handleGoodsSelectionChange = (selection) => {
  selectedGoods.value = selection
}

// 确认选择货品
const confirmGoodsSelection = () => {
  if (selectedGoods.value.length === 0) {
    ElMessage.warning('请选择至少一个货品')
    return
  }
  
  // 添加选中的货品到明细列表
  selectedGoods.value.forEach(goods => {
    // 检查是否已存在
    const exists = formData.orderItems.some(item => item.goodsId === goods.goodsId)
    if (!exists) {
      // 根据unitId查找单位名称
      const unit = unitList.value.find(u => u.id === goods.unitId)
      const unitName = unit ? unit.unitName : (goods.unitName || '')
      
      console.log('添加货品:', {
        goodsName: goods.goodsName,
        unitId: goods.unitId,
        找到的单位: unit,
        unitName: unitName,
        当前库存: goods.currentInventory
      })
      
      formData.orderItems.push({
        goodsId: goods.goodsId,
        goodsCode: goods.goodsCode,
        goodsName: goods.goodsName,
        specificationModel: goods.specModel,
        unitId: goods.unitId,
        unitName: unitName,
        currentInventory: goods.currentInventory || 0,  // ✅ 从货品数据中获取
        purchaseQuantity: goods.purchaseQuantity,
        inStockedQuantity: goods.inStockedQuantity || 0,
        unStockedQuantity: goods.unStockedQuantity,
        stockPositionId: null,
        thisTimeQuantity: 0,
        purchasePrice: goods.purchasePrice,
        upprice: 0,
        batchNo: '',
        productionDate: '',
        expireDate: '',
        remark: ''
      })
    }
  })
  
  goodsDialogVisible.value = false
  ElMessage.success(`已添加 ${selectedGoods.value.length} 个货品`)
}

// 计算明细项金额
const calculateItemAmount = (index) => {
  const item = formData.orderItems[index]
  if (item) {
    const quantity = parseFloat(item.thisTimeQuantity) || 0
    const unitPrice = parseFloat(item.purchasePrice) || 0
    item.upprice = quantity * unitPrice
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// 移除选中项
const handleRemoveSelected = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要移除的货品')
    return
  }
  
  ElMessageBox.confirm('确定要移除选中的货品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    selectedItems.value.forEach(item => {
      const index = formData.orderItems.findIndex(i => i.goodsId === item.goodsId)
      if (index !== -1) {
        formData.orderItems.splice(index, 1)
      }
    })
    ElMessage.success('移除成功')
  })
}

// 删除明细项
const removeItem = (index) => {
  ElMessageBox.confirm('确定要删除这个货品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formData.orderItems.splice(index, 1)
    ElMessage.success('删除成功')
  })
}

// 保存订单
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (formData.orderItems.length === 0) {
      ElMessage.warning('请至少添加一个货品')
      return
    }
    
    // 验证明细数据
    for (let i = 0; i < formData.orderItems.length; i++) {
      const item = formData.orderItems[i]
      
      if (!item.thisTimeQuantity || item.thisTimeQuantity <= 0) {
        ElMessage.error(`第${i + 1}个货品的本次入库数量必须大于0`)
        return
      }
      if (!item.stockPositionId) {
        ElMessage.error(`第${i + 1}个货品的入库库位不能为空`)
        return
      }
    }
    
    saveLoading.value = true
    
    // 准备提交数据 - 按照后端接口要求的格式
    const submitData = {
      stockInOrder: {
        stockInCode: formData.stockInCode,
        warehouseId: formData.warehouseId,
        stockInDate: formData.stockInDate,
        relatedOrderCode: formData.relatedOrderCode,
        supplierId: formData.supplierId,
        contactPerson: formData.contactPerson,
        contactPhone: formData.contactPhone,
        userId: formData.userId,
        remark: formData.remark,
        status: 0,
        inOutTypeId: formData.inOutTypeId
      },
      orderItems: formData.orderItems.map(item => ({
        goodsId: item.goodsId,
        unitId: item.unitId,
        thisTimeQuantity: item.thisTimeQuantity,
        stockPosition: item.stockPositionId,
        upprice: String(item.upprice || 0),
        batchDate: item.batchNo || '',
        productionDate: item.productionDate || '',
        expireDate: item.expireDate || '',
        itemRemark: item.remark || ''
      }))
    }
    
    console.log('提交数据:', submitData)
    
    const response = await proxy.http.post('/api/WarehousingManagement/SaveStockInOrder', submitData, false)
    
    console.log('保存响应:', response)
    
    if (response && response.success) {
      ElMessage.success('入库单保存成功')
      router.push('/wms.stockinorder/stockinorder')
    } else {
      ElMessage.error(response?.message || '保存失败')
    }
  } catch (error) {
    console.error('保存入库单失败:', error)
    ElMessage.error('保存入库单失败，请检查输入信息')
  } finally {
    saveLoading.value = false
  }
}

// 重置表单
const handleReset = () => {
  ElMessageBox.confirm('确定要重置所有数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value?.resetFields()
    formData.orderItems = []
    formData.relatedOrderCode = ''
    formData.supplierId = null
    formData.contactPerson = ''
    formData.contactPhone = ''
    selectedPurchaseOrder.value = null
    ElMessage.success('重置成功')
  })
}

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm('确定要离开吗？未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/wms.stockinorder/stockinorder')
  })
}

// 页面初始化
onMounted(async () => {
  // 设置默认日期
  formData.stockInDate = new Date().toISOString().split('T')[0]
  
  // 加载基础数据
  try {
    await Promise.all([
      fetchWarehouseList(),
      fetchUserList(),
      fetchSupplierList(),
      fetchUnitList(),
      fetchStorageLocationList()
    ])
    
    console.log('页面初始化完成')
  } catch (error) {
    console.error('页面初始化失败:', error)
    ElMessage.error('页面初始化失败，请刷新页面重试')
  }
})
</script>

<style scoped>
.stock-in-order-add-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.stock-in-form {
  margin-top: 20px;
}

.total-summary {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.summary-display {
  text-align: center;
  font-size: 16px;
}

.summary-item {
  color: #606266;
  margin: 0 15px;
  font-weight: 500;
}

.summary-item .count {
  color: #409eff;
  font-weight: bold;
}

.summary-item .amount {
  color: #e6a23c;
  font-weight: bold;
  font-size: 18px;
}

.summary-item.highlight {
  color: #e6a23c;
  font-weight: bold;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-content {
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-info {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
}

.search-section {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 表单样式 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stock-in-order-add-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>

